package com.gewu.pm.ui.activity.work;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gewu.pm.R;
import com.gewu.pm.aop.SingleClick;
import com.gewu.pm.app.AppActivity;
import com.gewu.pm.ui.activity.ImageSelectActivity;
import com.gewu.pm.ui.adapter.order.ImageUploadAdapter;
import com.gewu.pm.utils.MathUtils;
import com.gewu.pm.utils.MoneyInputHelper;
import com.gewu.pm.utils.TextStarUtils;
import com.gewu.pm.utils.eventbus.EventBean;
import com.gewu.pm.utils.eventbus.EventBusUtil;
import com.gewu.pm.utils.eventbus.EventCode;
import com.gewu.pm.http.glide.GlideApp;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 终端拜访信息填写页面
 */
public final class TerminalVisitInfoActivity extends AppActivity
        implements ImageSelectActivity.OnPhotoSelectListener {

    private static final int MAX_PROBLEM_IMAGE_COUNT = 5;  // 问题照片最多5张

    // 基本信息
    private TextView mVisitorLabel;
    private TextView mVisitorValue;
    private TextView mFacadePhotoLabel;
    private ImageView mFacadePhotoView;
    private ImageView mFacadePhotoDeleteView;
    private String mFacadePhotoPath;
    private TextView mProductPhotoLabel;
    private ImageView mProductPhotoView;
    private ImageView mProductPhotoDeleteView;
    private String mProductPhotoPath;
    private TextView mPurposeLabel;
    private EditText mPurposeEdit;
    private TextView mProblemLabel;
    private EditText mProblemEdit;
    private TextView mSummaryLabel;
    private EditText mSummaryEdit;

    // 问题照片
    private RecyclerView mProblemImagesView;
    private ImageUploadAdapter mProblemImageAdapter;
    private final List<String> mProblemImageList = new ArrayList<>();

    // 费用清单
    private EditText mPublicTransportEdit;
    private EditText mTaxiEdit;
    private EditText mSelfDriveEdit;
    private EditText mAccommodationEdit;
    private EditText mOtherExpenseEdit;
    private EditText mExpenseDetailEdit;
    private TextView mTotalExpenseView;

    // 提交按钮
    private TextView mSubmitButton;

    // 当前选择的图片类型
    private int mCurrentPhotoType = -1;  // -1-问题照片，0-门头照，1-产品陈列拍照

    public static void start(Context context) {
        Intent intent = new Intent(context, TerminalVisitInfoActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.terminal_visit_info_activity;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        // 基本信息
        mVisitorLabel = findViewById(R.id.tv_visitor_label);
        mVisitorValue = findViewById(R.id.tv_visitor_value);
        mFacadePhotoLabel = findViewById(R.id.tv_facade_photo_label);
        mFacadePhotoView = findViewById(R.id.iv_facade_photo);
        mFacadePhotoDeleteView = findViewById(R.id.iv_facade_photo_delete);
        mProductPhotoLabel = findViewById(R.id.tv_product_photo_label);
        mProductPhotoView = findViewById(R.id.iv_product_photo);
        mProductPhotoDeleteView = findViewById(R.id.iv_product_photo_delete);
        mPurposeLabel = findViewById(R.id.tv_purpose_label);
        mPurposeEdit = findViewById(R.id.et_purpose);
        mProblemLabel = findViewById(R.id.tv_problem_label);
        mProblemEdit = findViewById(R.id.et_problem);
        mSummaryLabel = findViewById(R.id.tv_summary_label);
        mSummaryEdit = findViewById(R.id.et_summary);

        // 问题照片
        mProblemImagesView = findViewById(R.id.rv_problem_images);

        // 费用清单
        mPublicTransportEdit = findViewById(R.id.et_public_transport);
        mTaxiEdit = findViewById(R.id.et_taxi);
        mSelfDriveEdit = findViewById(R.id.et_self_drive);
        mAccommodationEdit = findViewById(R.id.et_accommodation);
        mOtherExpenseEdit = findViewById(R.id.et_other_expense);
        mExpenseDetailEdit = findViewById(R.id.et_expense_detail);
        mTotalExpenseView = findViewById(R.id.tv_total_expense);

        // 提交按钮
        mSubmitButton = findViewById(R.id.btn_submit);

        // 设置必填标记
        TextStarUtils.setRequiredText(mFacadePhotoLabel, getString(R.string.facade_photo));
        TextStarUtils.setRequiredText(mProductPhotoLabel, getString(R.string.product_display_photo));
        TextStarUtils.setRequiredText(mPurposeLabel, getString(R.string.purpose_of_visit));
        TextStarUtils.setRequiredText(mSummaryLabel, getString(R.string.visit_summary));

        // 设置单张图片点击事件
        mFacadePhotoView.setOnClickListener(v -> {
            mCurrentPhotoType = 0;  // 门头照
            ImageSelectActivity.start(this, 1, this);
        });
        mProductPhotoView.setOnClickListener(v -> {
            mCurrentPhotoType = 1;  // 产品陈列拍照
            ImageSelectActivity.start(this, 1, this);
        });

        // 设置图片删除按钮点击事件
        mFacadePhotoDeleteView.setOnClickListener(v -> deleteFacadePhoto());
        mProductPhotoDeleteView.setOnClickListener(v -> deleteProductPhoto());

        // 设置问题照片网格（3列）
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 3);
        mProblemImagesView.setLayoutManager(gridLayoutManager);

        // 设置问题照片适配器
        mProblemImageAdapter = new ImageUploadAdapter(this, MAX_PROBLEM_IMAGE_COUNT, position -> {
            // 删除图片
            mProblemImageList.remove(position);
            updateProblemImageList();
        });
        // 设置占位图为 add_ic
        mProblemImageAdapter.setPlaceholderResId(R.drawable.add_ic);
        // 启用占位文字显示
        mProblemImageAdapter.setShowPlaceholderText(true);
        mProblemImageAdapter.setPlaceholderTextPrefix("上传图片");

        // 设置添加图片监听
        mProblemImageAdapter.setOnAddListener(() -> {
            // 打开图片选择
            int remainCount = MAX_PROBLEM_IMAGE_COUNT - mProblemImageList.size();
            if (remainCount > 0) {
                mCurrentPhotoType = -1;  // 标记为问题照片
                ImageSelectActivity.start(this, remainCount, this);
            } else {
                toast("最多只能选择" + MAX_PROBLEM_IMAGE_COUNT + "张图片");
            }
        });

        mProblemImagesView.setAdapter(mProblemImageAdapter);

        // 设置金额输入限制
        MoneyInputHelper.setMoneyInput(mPublicTransportEdit);
        MoneyInputHelper.setMoneyInput(mTaxiEdit);
        MoneyInputHelper.setMoneyInput(mSelfDriveEdit);
        MoneyInputHelper.setMoneyInput(mAccommodationEdit);
        MoneyInputHelper.setMoneyInput(mOtherExpenseEdit);

        // 设置费用输入监听
        setupExpenseWatchers();

        // 设置点击事件
        setOnClickListener(mSubmitButton);
    }

    @Override
    protected void initData() {
        // 初始化问题照片列表
        updateProblemImageList();
    }

    /**
     * 设置费用输入监听器
     */
    private void setupExpenseWatchers() {
        TextWatcher watcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                calculateTotalExpense();
            }
        };

        mPublicTransportEdit.addTextChangedListener(watcher);
        mTaxiEdit.addTextChangedListener(watcher);
        mSelfDriveEdit.addTextChangedListener(watcher);
        mAccommodationEdit.addTextChangedListener(watcher);
        mOtherExpenseEdit.addTextChangedListener(watcher);
    }

    /**
     * 计算费用合计
     */
    private void calculateTotalExpense() {
        double total = 0.0;

        // 公共交通费
        String publicTransport = mPublicTransportEdit.getText().toString().trim();
        if (!TextUtils.isEmpty(publicTransport)) {
            try {
                total = MathUtils.moneyAdd(total, Double.parseDouble(publicTransport));
            } catch (NumberFormatException e) {
                // 忽略格式错误
            }
        }

        // 打车费
        String taxi = mTaxiEdit.getText().toString().trim();
        if (!TextUtils.isEmpty(taxi)) {
            try {
                total = MathUtils.moneyAdd(total, Double.parseDouble(taxi));
            } catch (NumberFormatException e) {
                // 忽略格式错误
            }
        }

        // 自驾车费
        String selfDrive = mSelfDriveEdit.getText().toString().trim();
        if (!TextUtils.isEmpty(selfDrive)) {
            try {
                total = MathUtils.moneyAdd(total, Double.parseDouble(selfDrive));
            } catch (NumberFormatException e) {
                // 忽略格式错误
            }
        }

        // 住宿费
        String accommodation = mAccommodationEdit.getText().toString().trim();
        if (!TextUtils.isEmpty(accommodation)) {
            try {
                total = MathUtils.moneyAdd(total, Double.parseDouble(accommodation));
            } catch (NumberFormatException e) {
                // 忽略格式错误
            }
        }

        // 其他费用
        String otherExpense = mOtherExpenseEdit.getText().toString().trim();
        if (!TextUtils.isEmpty(otherExpense)) {
            try {
                total = MathUtils.moneyAdd(total, Double.parseDouble(otherExpense));
            } catch (NumberFormatException e) {
                // 忽略格式错误
            }
        }

        // 显示合计
        mTotalExpenseView.setText(String.format("%.2f", total) + " 元");
    }

    /**
     * 更新问题照片列表
     */
    private void updateProblemImageList() {
        List<String> displayList = new ArrayList<>(mProblemImageList);

        // 如果未满5张，添加相机图标
        if (mProblemImageList.size() < MAX_PROBLEM_IMAGE_COUNT) {
            displayList.add("camera");
        }

        mProblemImageAdapter.setData(displayList);
    }

    /**
     * 更新单张图片显示
     */
    private void updateSinglePhoto(ImageView imageView, ImageView deleteView, String imagePath) {
        if (!TextUtils.isEmpty(imagePath) && new File(imagePath).exists()) {
            GlideApp.with(this)
                    .load(new File(imagePath))
                    .placeholder(R.drawable.add_ic)
                    .error(R.drawable.add_ic)
                    .into(imageView);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            deleteView.setVisibility(View.VISIBLE);
        } else {
            imageView.setImageResource(R.drawable.add_ic);
            imageView.setScaleType(ImageView.ScaleType.CENTER);
            deleteView.setVisibility(View.GONE);
        }
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == mSubmitButton) {
            // 验证必填项
            if (TextUtils.isEmpty(mFacadePhotoPath)) {
                toast("请上传门头照");
                return;
            }
            if (TextUtils.isEmpty(mProductPhotoPath)) {
                toast("请上传产品陈列拍照");
                return;
            }
            if (TextUtils.isEmpty(mPurposeEdit.getText().toString().trim())) {
                toast("请输入走访目的");
                return;
            }
            if (TextUtils.isEmpty(mSummaryEdit.getText().toString().trim())) {
                toast("请输入拜访总结");
                return;
            }

            // 计算费用合计
            calculateTotalExpense();
            String totalText = mTotalExpenseView.getText().toString().trim();
            String totalAmount = totalText.replace(" 元", "").trim();

            // 发送 EventBus 事件
            EventBusUtil.sendEvent(new EventBean<>(EventCode.VISIT_INFO_SUBMIT, totalAmount));

            // 显示提示
            toast("提交成功");

            // 关闭页面
            finish();
        }
    }

    /**
     * 删除门头照
     */
    @SingleClick
    private void deleteFacadePhoto() {
        mFacadePhotoPath = null;
        updateSinglePhoto(mFacadePhotoView, mFacadePhotoDeleteView, mFacadePhotoPath);
        toast("已删除门头照");
    }

    /**
     * 删除产品陈列拍照
     */
    @SingleClick
    private void deleteProductPhoto() {
        mProductPhotoPath = null;
        updateSinglePhoto(mProductPhotoView, mProductPhotoDeleteView, mProductPhotoPath);
        toast("已删除产品陈列拍照");
    }

    /**
     * {@link ImageSelectActivity.OnPhotoSelectListener}
     * 图片选择回调
     */
    @Override
    public void onSelected(List<String> images) {
        if (images != null && !images.isEmpty()) {
            if (mCurrentPhotoType == -1) {
                // 问题照片
                mProblemImageList.addAll(images);
                updateProblemImageList();
            } else if (mCurrentPhotoType == 0) {
                // 门头照
                String selectedImage = images.get(0);
                mFacadePhotoPath = selectedImage;
                updateSinglePhoto(mFacadePhotoView, mFacadePhotoDeleteView, mFacadePhotoPath);
            } else if (mCurrentPhotoType == 1) {
                // 产品陈列拍照
                String selectedImage = images.get(0);
                mProductPhotoPath = selectedImage;
                updateSinglePhoto(mProductPhotoView, mProductPhotoDeleteView, mProductPhotoPath);
            }
        }
    }

    @Override
    public void onCancel() {
        // 取消选择
    }
}
